package online.zhangwenzhe.common.security;

import org.springframework.util.Assert;

/**
 * Description
 * 当前用户信息
 * 没有登陆时，获取到userDetails为null
 * eg:
 *     @RequestMapping(value = "/get", method = RequestMethod.GET)
 *     public String get() {
 *         UserDetails userDetails = UserContext.getUserDetails();
 *
 *         String msg = "/test/get is ok\n";
 *         if (userDetails != null) {
 *             msg += userDetails.getUserId();
 *         }
 *         return msg;
 *     }
 *
 * @author zhangwenzhe
 * @since 2019-02-26
 */
public class UserContext {
    private static final ThreadLocal<UserDetails> USER_DETAILS_THREAD_LOCAL = new ThreadLocal<>();

    public static UserDetails getUserDetails() {
        return USER_DETAILS_THREAD_LOCAL.get();
    }

    public static void setUserDetails(UserDetails token) {
        Assert.notNull(token, "UserDetails不可设置为空");
        USER_DETAILS_THREAD_LOCAL.set(token);
    }

    public static void removeUserDetails() {
        USER_DETAILS_THREAD_LOCAL.remove();
    }

}
